import datetime
from app.db.models.jobs import Job
from app.db.models.tasks import Task


class JobIpv6SupportStatus:

    def service(self):
        print(f"{datetime.datetime.now()} 开始同步......")
        aggregate = [
            {'$match': {'taskType': "ipv6", "status": "completed"}},
            {'$group': {'_id': '$jobId', 'id': {'$last': '$_id'}}},
            {'$lookup': {'from': "tasks", 'localField': "id", 'foreignField': "_id", 'as': "task"}},
        ]

        tasks = Task.objects.aggregate(aggregate)

        ipv6_support_job_ids = []
        ipv6_nonsupport_job_ids = []
        for item in tasks:
            if item.get('task'):
                task = item.get('task')[0]
            else:
                continue

            job_id = task.get('jobId')
            is_support_ipv6 = task.get("result", {}).get("addition", {}).get("is_support_ipv6", "")

            is_support_ipv6_str = "nonsupport"
            if is_support_ipv6:
                is_support_ipv6_str = "support"

            if is_support_ipv6_str == "nonsupport":
                ipv6_nonsupport_job_ids.append(job_id)
            elif is_support_ipv6_str == "support":
                ipv6_support_job_ids.append(job_id)

        Job.objects(pk__in=ipv6_support_job_ids).update(isSupportIpv6="support")
        Job.objects(pk__in=ipv6_nonsupport_job_ids).update(isSupportIpv6="nonsupport")
        print(f"{datetime.datetime.now()} 同步完成")
